package com.redwine.app.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.redwine.app.APP;
import com.redwine.app.ProcurementDetailActivity;
import com.redwine.app.PublishedSourcesDetailActivity;
import com.redwine.app.R;
import com.redwine.app.adapter.BannerViewPager;
import com.redwine.app.adapter.HomeAdapter;
import com.redwine.app.net.GsonRequest;
import com.redwine.app.net.NetworkConstants;
import com.redwine.app.net.responses.HomePageBannerResponse;
import com.redwine.app.net.responses.HomePageResponse;
import com.redwine.app.net.responses.SendMsgEvent;
import com.redwine.app.utils.DimenUtils;
import com.redwine.app.utils.Global;
import com.redwine.app.utils.NetUtil;
import com.redwine.app.view.EmptyView;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

import static com.redwine.app.utils.Utils.showToast;

/**
 * 首页资讯列表页
 */
public class HomeFragment extends BaseFragment {

    private View rootView;
    private View headerView;
    private BannerViewPager bannerViewPager;
    private RelativeLayout viewFeedBannerInner;
    @ViewInject(R.id.common_refresh_list_view)
    private PullToRefreshListView mListView;
    @ViewInject(R.id.empty_view)
    private EmptyView emptyView;
    private int page = 1;//默认加载第一页
    private List<HomePageBannerResponse.DataEntity> responseData = new ArrayList<>();
    private HomeAdapter homeAdapter;

    @ViewInject(R.id.header_title)
    private TextView headerTitle;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (null != rootView) {
            ViewGroup parent = (ViewGroup) rootView.getParent();
            if (null != parent) {
                parent.removeView(rootView);
            }
        } else {
            rootView = inflater.inflate(R.layout.activity_common_refresh_list_view, container, false);
            ViewUtils.inject(this, rootView);
            EventBus.getDefault().register(this);
            initView();
            requestBannerData(true);
        }
        return rootView;
    }

    private void initView() {
        headerTitle.setText(getString(R.string.home));
        mListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                page = 1;
                requestBannerData(false);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                page += 1;
                requestListData();
            }
        });
        mListView.setOnActionMoveListener(new PullToRefreshBase.OnActionMove() {
            @Override
            public void onMove(boolean isMove) {
                setUpdateTime(mListView);
            }
        });
        mListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        headerView = LayoutInflater.from(getActivity()).inflate(R.layout.activity_main_header, null);
        mListView.getRefreshableView().addHeaderView(headerView);
        homeAdapter = new HomeAdapter(getActivity());
        mListView.setAdapter(homeAdapter);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                int newPosition = position - mListView.getRefreshableView().getHeaderViewsCount();
                HomePageResponse.DataEntityX.DataEntity dataEntity = homeAdapter.getData().get(newPosition);
                Intent intent = new Intent(getActivity(), ProcurementDetailActivity.class);
                intent.putExtra(PublishedSourcesDetailActivity.SHOP_NAME, dataEntity.getTitle());
                intent.putExtra(PublishedSourcesDetailActivity.SHOP_UID, Global.user.getUid());
                intent.putExtra(PublishedSourcesDetailActivity.SHOP_ID, dataEntity.getId());
                startActivity(intent);
            }
        });
        setHiddenView(emptyView);
    }


    /**
     * 更新banner显示
     * 作者：gassion on 17/8/16 23:31
     * 最可怕的敌人，就是没有坚强的信念。
     */
    private void updateBannerView() {
        if (null != responseData && !responseData.isEmpty()) {
            headerView.setVisibility(View.VISIBLE);
            bannerViewPager = (BannerViewPager) headerView.findViewById(R.id.main_banner_Layout);
            viewFeedBannerInner = (RelativeLayout) headerView.findViewById(R.id.view_feed_banner_inner);
            int screenWidth = DimenUtils.getWindowsWidth(getActivity()) - DimenUtils.dip2px(16);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, screenWidth / 2);
            viewFeedBannerInner.setLayoutParams(params);
            bannerViewPager.setRootView(headerView);
            bannerViewPager.setVisibility(View.VISIBLE, DimenUtils.dp2px(20));
            bannerViewPager.setPagerAdapter(new BannerViewPager.BannerViewPagerAdapter() {
                @Override
                public int bannerImageCount() {
                    return responseData.size();
                }

                @Override
                public String bannerImageUrlAtIndex(int index) {
                    return responseData.get(index).getPic();
                }

                @Override
                public void bannerDidSelectAtIndex(int index) {
                    // 1 供应 2 采购
                    if ("1".equals(responseData.get(index).getType())) {
                        Intent intent = new Intent(getActivity(), PublishedSourcesDetailActivity.class);
                        intent.putExtra(PublishedSourcesDetailActivity.SHOP_NAME, "");
                        intent.putExtra(PublishedSourcesDetailActivity.SHOP_UID, responseData.get(index).getData_uid());
                        intent.putExtra(PublishedSourcesDetailActivity.SHOP_ID, responseData.get(index).getData_id());
                        startActivity(intent);
                    } else {
                        Intent intent = new Intent(getActivity(), ProcurementDetailActivity.class);
                        intent.putExtra(PublishedSourcesDetailActivity.SHOP_NAME, "");
                        intent.putExtra(PublishedSourcesDetailActivity.SHOP_UID, responseData.get(index).getData_uid());
                        intent.putExtra(PublishedSourcesDetailActivity.SHOP_ID, responseData.get(index).getData_id());
                        startActivity(intent);
                    }
                }
            });
        }
    }

    /**
     * 请求banner数据
     */
    private void requestBannerData(boolean isLoading) {
        if (!NetUtil.checkNet(getActivity())) {
            showToast(R.string.generic_check);
            setErrorView(emptyView, null);
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (null != mListView)
                        mListView.onRefreshComplete();

                }
            }, 500);
            return;
        }

        if (isLoading)
            showWaiting();
        String url = NetworkConstants.HOME_PAGE_BANNER_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("uid", Global.user.getUid());
        GsonRequest<HomePageBannerResponse> request = new GsonRequest<>(url, Request.Method.POST,
                HomePageBannerResponse.class, false, params, new Response.Listener<HomePageBannerResponse>() {
            @Override
            public void onResponse(HomePageBannerResponse response) {
                if (response.isSuccess()) {
                    responseData = response.getData();
                    updateBannerView();
                }
                requestListData();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                requestListData();
            }
        });
        APP.getInstance().getRequestQueue().add(request);
    }

    /**
     * 请求列表数据
     */
    private void requestListData() {
        if (!NetUtil.checkNet(getActivity())) {
            if (homeAdapter.getData().isEmpty()) {
                setErrorView(emptyView, null);
            }
            showToast(R.string.generic_check);
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (null != mListView)
                        mListView.onRefreshComplete();

                }
            }, 500);
            return;
        }

        String url = NetworkConstants.HOME_PAGE_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("size", "20");
        params.put("page", String.valueOf(page));
        GsonRequest<HomePageResponse> request = new GsonRequest<>(url, Request.Method.POST,
                HomePageResponse.class, false, params, new Response.Listener<HomePageResponse>() {
            @Override
            public void onResponse(HomePageResponse response) {
                dismissWaiting();
                if (null != mListView)
                    mListView.onRefreshComplete();
                if (response.isSuccess()) {
                    HomePageResponse.DataEntityX data = response.getData();
                    updateCommentView(data);
                } else {
                    if (headerView.getVisibility() != View.VISIBLE) {
                        setEmptyView(emptyView, null);
                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                showToast(R.string.generic_check);
                dismissWaiting();
                if (null != mListView)
                    mListView.onRefreshComplete();
                if (headerView.getVisibility() != View.VISIBLE) {
                    setEmptyView(emptyView, null);
                }
            }
        });
        APP.getInstance().getRequestQueue().add(request);
    }

    private void updateCommentView(HomePageResponse.DataEntityX responseData) {
        if (headerView.getVisibility() != View.VISIBLE && null != responseData && null != responseData.getData() && responseData.getData().isEmpty()) {
            setEmptyView(emptyView, mListView);
        }

        List<HomePageResponse.DataEntityX.DataEntity> responseDataData = responseData.getData();
        homeAdapter.setData(page, responseDataData);
        if (responseData.getPage() != responseData.getAllpage()) {
            mListView.setMode(PullToRefreshBase.Mode.BOTH);
        } else {
            mListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        }
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("MainScreen");

    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("MainScreen");
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onStart() {
        super.onStart();
    }


    public void onEventMainThread(SendMsgEvent event) {
        if (event.getSendType() == SendMsgEvent.REFURBISH_MAIN_DATA) {
            if (null != mListView) {
                mListView.setRefreshing();
            } else {
                requestBannerData(true);
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void emptyOnclick() {
        setHiddenView(emptyView);
        if (null != mListView) {
            mListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    mListView.setRefreshing();
                }
            }, 500);
        } else {
            requestBannerData(true);
        }
    }

}